package cn.youyeku.zsxh.ui.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewHolder {

	private SparseArray<View> mviews;
	private Context context;
	private View mConvertView;
	private int position;

	public ViewHolder(Context context, ViewGroup parent, int layoutId,
					  int position) {

		this.position = position;
		this.mviews = new SparseArray<View>();

		this.mConvertView = LayoutInflater.from(context).inflate(layoutId,
				parent, false);
		mConvertView.setTag(this);
	}


	public static ViewHolder getInstance(Context context, View convertView,
										 ViewGroup parent, int layoutId, int position) {
		if (convertView == null) {
			return new ViewHolder(context, parent, layoutId, position);
		} else {
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.position=position;
			return holder;
		}
	}

	/**
	 * 获得布局
	 * @return
	 */
	public View getConvertView(){
		return mConvertView;
	}

	/**
	 * 根据控件id 获得控件
	 * @param viewid
	 * @return
	 */
	public <T extends View> T getView(int viewid){
		View view=mviews.get(viewid);
		if(view==null){
			view=mConvertView.findViewById(viewid);
			mviews.put(viewid, view);
		}
		return (T) view;
	}



	/**
	 * 实现通用方法
	 * 以后可以自定义实现
	 * 1.给textview 设置文字
	 */
	public ViewHolder setText(int viewId,String text){
		TextView textView=getView(viewId);
		textView.setText(text);
		return this;
	}

	/**
	 * 2.给imageview设置 图片
	 */
	public ViewHolder setImageBitmap(int viewId,Bitmap bitmap){
		ImageView imageView=getView(viewId);
		imageView.setImageBitmap(bitmap);
		return this;
	}


	/**
	 * 3.给图片设置图片资源
	 */
	public ViewHolder setImageResource(int viewid,int resId){
		ImageView imageView=getView(viewid);
		imageView.setImageResource(resId);
		return this;
	}

}
